package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"strconv"
	"work/src/work/global"
	"work/src/work/internal/model"
	"work/src/work/rabbitmq"
)

type ChatHandler struct {
}

func NewChatHandler() *ChatHandler {
	return &ChatHandler{}
}
func (c *ChatHandler) Chat(g *gin.Context) {
	userId, err := strconv.Atoi(g.Query("user_id"))
	if err != nil {
		return
	}

	conn, err := global.Upgrader.Upgrade(g.Writer, g.Request, nil)
	if err != nil {
		return
	}

	node := global.Node{
		Conn: conn,
		Data: make(chan []byte, 40),
	}
	global.CliMap[userId] = node

	go func(node global.Node) {
		for {
			_, message, err2 := node.Conn.ReadMessage()
			if err2 != nil {
				return
			}

			var msg model.Send
			json.Unmarshal(message, &msg)

			rabbitmqs := rabbitmq.NewRabbitMQPubSub("chat_work")
			rabbitmqs.PublishPub(string(message))

			//global.CliMap[msg.ToUserId].Data <- message
		}
	}(node)

	go func(node global.Node) {
		for {
			data := <-node.Data
			err := node.Conn.WriteMessage(websocket.TextMessage, data)
			if err != nil {
				return
			}

		}
	}(node)
}
